//index.js
//获取应用实例
const app = getApp()
import Dialog from '../../dist/dialog/dialog';
const util = require('../../utils/timeTool.js');
const util1 = require('../../utils/util.js');
Page({
  data: {
    current:0,
    //按产品要求，此处的校验移到提现接口，默认永远不做校验
    isnewPeople:null,
    bankCard: false,
    toView:"",
    emptywp: false,
    btnIndex: '3',
    temPrc:[],
    page: {
      "pageNumber": 1,
      "pageSize": 5,
      total: 0,
      totalPages: 0,
    },
    userInfo: {},
    id: "",
    myActivesList: [],
    statusList: {
      '0': '未开始',
      '1': '进行中',
      '2': '已结束',
      '3': '已取消',
      '4': '未开始'
    },
    isClicked:false,//点击的初始数据
    hiddenmodalput: false,
    codeTime: 0,
    codeStatus: false,
    topic: '',
    code: '',
    type: "phone",
    key: "telphone",

// 、、、、、、、、、
    processing:[],//进行中的活动
    noStarted:[],//未开始
    ontdata1:'',
    ontdata2:'',
    history:[],     //已结束
    ThreeMessage:null,
    isRedPoint:false,   //是否存在红点
    activityTheme: [
      {
        'name': '团购',
        'theme': '团购优惠，尽在此时',
        'pointType': 'yqlw_welcome_commodity',
        'type': 1
      },
      {
        'name': '打游戏',
        'theme': '大吉大利，今晚吃鸡',
        'pointType': 'yqlw_welcome_service',
        'type': 2
      },
      {
        'name': '运动',
        'theme': '今晚去运动吧',
        'pointType': 'yqlw_welcome_sports',
        'type': 3
      },
      {
        'name': '宴请',
        'theme': '一起吃饭，不见不散',
        'pointType': 'yqlw_welcome_banquet',
        'type': 4
      },
      {
        'name': '团建',
        'theme': '团结就是力量',
        'pointType': 'yqlw_welcome_party',
        'type': 5
      },
      {
        'name': '婚礼',
        'theme': '敬备喜筵，恭请光临',
        'pointType': 'yqlw_welcome_wedding',
        'type': 6
      },
      {
        'name': '大型活动',
        'theme': '大型活动也轻松',
        'pointType': 'yqlw_welcome_activity',
        'type': 7
      },
      {
        'name': '会议',
        'theme': '一起开个会吧',
        'pointType': 'yqlw_welcome_meeting',
        'type': 8
      },
      {
        'name': '商家活动',
        'theme': '我们诚挚邀请您参加',
        'pointType': 'yyqlw_welcome_service',
        'type': 9
      },
       {
        'name': '商会活动',
         'theme': '功能强大，体验流畅，适合各种类型活动',
        'pointType': 'yyqlw_welcome_service',
        'type': 10
      },
      {
        'name': '公益',
        'theme': '功能强大，体验流畅，适合各种类型活动',
        'pointType': 'yyqlw_welcome_service',
        'type': 11
      },
      {
        'name': '生日',
        'theme': '功能强大，体验流畅，适合各种类型活动',
        'pointType': 'yyqlw_welcome_service',
        'type': 12
      },
    ],
    onGoingListCount:'0',
    ontStartListCount:'0',
    overListCount:'0',
    birthdayListCount:'',
    birthdayList:[],
    address:null,
    bannerList:null,
    island: false,
    loginShow: false,
  },
  ReleaseAct(e) {
    this.setData({
      btnIndex: e.target.dataset.btnindex
    })
  },
  ReleaseUnAct() {
    this.setData({
      btnIndex: '3'
    })
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  onLoad: function(options) {
    var that = this
    // app.TestBuriedPoint('')
    that.getBannerList()
  },
  onShow: function(){ 
    var that = this;
    // var phone = wx.getStorageSync('phone');
    that.setData({
      current:0,
    })
    //埋点
    if (that.data.isnewPeople == true) {
      app.TestBuriedPoint('yqlw_welcome_pv')
    } else {
      app.TestBuriedPoint('yqlw_home_taba')
    }

    app.getUserInfo(function (userInfo) {
      that.toggle("userInfo", userInfo);
      
    });
    that.setData({
      'page.pageNumber': 1,
      myActivesList: []
    })
    that.loadListData();
    that.getThreeMessage()
    that.getRedPointStatus()
    wx.getSetting({
      success: (res) => {
        console.log('授权', res)
        if (wx.getStorageSync('uid')) {
          that.setData({
            island: true
          })
          //获取头像及名称
          that.getUserInfo()
        }else{
          that.setData({
            island: false
          })
        }
      }
    })
  },
  loadListData: function() {
    var that = this;
    app.req({
      url: "wechat/activity/myActivity",
      method: "post",
      data: {
        "pageNumber": that.data.page.pageNumber,
        "pageSize": that.data.page.pageSize,
      },
      success: function(res) {
        console.log(res);
        if (res.code == 200) {
          for (var i = 0; i < res.data.processing.length; i++) {
            res.data.processing[i].createTime = util.itemDateToShow(res.data.processing[i].createTime, 1, true, false).substring(5)
            if ((res.data.processing[i].actType == 1 && res.data.processing[i].type == 2) || res.data.processing[i].actType ==12) {
              res.data.processing[i].actEndTime = util.itemDateToShow(res.data.processing[i].actEndTime, 1, false, false).substring(5, 11)
            }
          }
          for (var i = 0; i < res.data.noStarted.length; i++) {
            res.data.noStarted[i].createTime = util.itemDateToShow(res.data.noStarted[i].createTime, 1, true, false).substring(5)
            if (res.data.noStarted[i].actType == 12) {
              res.data.noStarted[i].actEndTime = util.itemDateToShow(res.data.noStarted[i].actEndTime, 1, false, false).substring(5, 11)
            }
          }
          for (var i = 0; i < res.data.history.rows.length;i++){
            res.data.history.rows[i].actStartTime = util.formatTime4(res.data.history.rows[i].actStartTime)
          }
          that.setData({
            history: res.data.history.rows,
            noStarted: res.data.noStarted,
            processing: res.data.processing,
            overListCount: res.data.history.total,
            totalPages: res.data.history.totalPages,
          })
          that.toggle('page.totalPages', that.data.totalPages)
          
        }else {
            wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
        }
      }
    });
  },
  loadListData1: function () {
    var that = this;
    app.req({
      url: "wechat/activity/myActivity",
      method: "post",
      data: {
        "pageNumber": that.data.page.pageNumber,
        "pageSize": that.data.page.pageSize,
      },
      success: function (res) {
        console.log(res);
        if (res.code == 200) {
          for (var i = 0; i < res.data.history.rows.length; i++) {
            res.data.history.rows[i].actStartTime = util.formatTime4(res.data.history.rows[i].actStartTime)
          }
          var historys = res.data.history.rows
          that.setData({
            history: that.data.history.concat(historys)
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  clickMenu: function (e) {
    var id = e.currentTarget.dataset.id;
    this.setData({
      toView: id
    })
  },
  //创建活动
  addParty() {
    this.checkDetail('/pages/party/party');
  },
  //创建运动
  addSport() {
    this.checkDetail('/pages/sport/sport');
  },
  //创建自定义
  // addCustomItem() {
  //   this.checkDetail('/pages/custom/custom');
  // },
  checkDetail(url) {
    var self = this;
    if (!self.data.isClicked) {
      app.req({
        url: "wechat/user/getUserInformation",
        method: "post",
        data: {},
        success: function (res) {
          console.log(res);
          if (res && res.code == 200) {
            if (res.data.telphone == '') {
              self.setData({
                hiddenmodalput: true
              });  
            } else {
              wx.navigateTo({
                url: url
              });
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })

      self.setData({
        isClicked:true
      })

      setTimeout(function () {
        self.setData({
          isClicked:false
        })
      },500);
    }
  },
  //详情
  toInfo(e) {
    wx.navigateTo({
      url: '/pages/register/register?id=' + e.currentTarget.dataset.id
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      'page.pageNumber': 1,
      history: []
    })
    this.loadListData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var data = this.data;
    console.log('加载更多1')
    if (data.page.totalPages > data.page.pageNumber) {
      this.setData({
        'page.pageNumber': data.page.pageNumber + 1
      })
      console.log('加载更多2', this.data.page.pageNumber)
      this.loadListData1();
    }
  },

  formatTime(dateTime) {
    var date = new Date((dateTime.replace(/\-/g, "/")));
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    return year + '年' + month + '月' + day + '日';
  },

  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: false
    });
  },
  
  //确认  
  confirm: function () {
    var data = {};
    var that = this;
    var val = that.data.topic.trim();
    console.log(val);
    if (!val) {
      wx.showToast({
        title: "手机号必填",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var type = that.data.type;
    switch (type) {
      case "phone":
        var phonePattern = /^1[3456789]\d{9}$/;
        if (!phonePattern.test(val)) {
          wx.showToast({
            title: "手机号格式错误",
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (that.data.code == '') {
          wx.showToast({
            title: "请输入验证码",
            icon: 'none',
            duration: 2000
          })
          return;
        }
        break;
    }
    data[that.data.key] = val;
    console.log(this.data.code);
    console.log(this.data.topic.trim());
    if (that.data.key == 'telphone') {
      app.req({
        url: "wechat/sys/judgeCode?code=" + this.data.code + "&telphone=" + this.data.topic.trim(),
        data: {},
        method: "post",
        success: function (res) {
          if (res) {
            that.saveInfo(data);
          } else {
            that.setData({
              hiddenmodalput: true
            }); 
            wx.showToast({
              title: '请输入正确的验证码',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      that.saveInfo(data);
    }
  },
  saveInfo(data) {
    var that = this;
    app.getUserInfo(function (userInfo) {
      app.req({
        url: "wechat/user/updateUserInformation",
        data: data,
        method: "post",
        success: function (res) {
          if (200 == res.code) {
            app.personalData(function (e) {
            })
            that.setData({
              hiddenmodalput: false
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    });
  },

  topicInput: function (e) {
    var topic = e.detail.value,
      currentLength = topic.length;
    if (currentLength > this.data.maxLength) {
      wx.showToast({
        title: '输入文字数量已达到上限',
        icon: 'none',
        duration: 2000
      })
      return this.data.topic;
    }
    this.setData({
      topic: topic,
      currentLength: currentLength
    })
  },

  codeInput(e) {
    this.setData({
      code: e.detail.value
    })
  },
  newUserJump1() {
    var that = this
    getApp().mtj.trackEvent('yqlw_open_blessing');
    if (!that.data.island) {
      that.landbtn()
    } else {
    // wx.navigateTo({
    //   url: '/pages/sport/sport'
    // });
      wx.navigateToMiniProgram({
        appId: app.globalData.blessingAppId,
        envVersion: app.globalData.activityMiniEnvVersion,
        path: 'pages/index/index',
        success(res) {
          console.log(res);
        }
      })
    }
  },
  sendCode() {
    var phone = this.data.topic.trim();
    var phonePattern = /^((\d{3}-\d{8}|\d{4}-\d{7,8})|(1[3|5|7|8][0-9]{9}))$/;
    if (!phonePattern.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var that = this;
    app.req({
      url: "wechat/sys/sendCode?telphone=" + phone,
      data: {},
      method: "post",
      success: function (res) {
        console.log(res)
        if (200 == res.code) {
          wx.showToast({
            title: '验证码发送成功，请注意查收',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            codeTime: 120,
            codeStatus: true
          })
          var currentTime = that.data.codeTime
          var interval = setInterval(function () {
            currentTime--;
            that.setData({
              codeTime: currentTime
            })
            if (currentTime == 0) {
              clearInterval(interval)
              that.setData({
                codeTime: 0,
                codeStatus: false
              })
            }
          }, 1000)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  getUserInfo: function () {
    var that = this;
    app.req({
      url: "wechat/user/getUserInformation",
      method: "post",
      data: {},
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            isnewPeople: res.data.newPeople,
            address:res.data.address
          });
        } else {
          // wx.showToast({
          //   title: res.msg,
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '一起来往，人际来往高效助手',
      imageUrl: 'https://img.yiqilaiwang.com/b0fcfd55-3c81-435b-9966-06c62903a5d3.png'
    }
  },


  /**
   * 以上为老版本代码逻辑，后期删除
   * 以下0314新的UI版本
   * 包括新用户首页和老用户首页
   */

  // 新用户
  newUserJump: function(option){
    var that = this
    if (!that.data.island) {
      that.landbtn()
    } else {
    var pointType = that.data.activityTheme[option.currentTarget.dataset.title].pointType
    app.TestBuriedPoint(pointType)
    var name = that.data.activityTheme[option.currentTarget.dataset.title].name
    var theme = that.data.activityTheme[option.currentTarget.dataset.title].theme
    var type = that.data.activityTheme[option.currentTarget.dataset.title].type
    console.log(name, theme,type)
    if(type==4){
      getApp().mtj.trackEvent('yqlw_act_banquet');
    } else if(type == 8) {
      getApp().mtj.trackEvent('yqlw_act_meeting');
    } else if (type == 3) {
      getApp().mtj.trackEvent('yqlw_act_sports');
    }
    wx.navigateTo({
      url: '/pages/party/party?name=' + name + '&theme=' + theme + '&type=' + type
    });
    }
  },
  //活动列表
  toactivityList: function (option) {
    if (!this.data.island) {
      this.landbtn()
    } else {
    let type = option.currentTarget.dataset.title
    if (type == 1){
      app.TestBuriedPoint('yqlw_list_conduct','yqlw_list_pv')
      // app.TestBuriedPoint('yqlw_list_pv')
    }else if(type == 2){
      app.TestBuriedPoint('yqlw_list_notyetbegun','yqlw_list_pv')
      // app.TestBuriedPoint('yqlw_list_pv')
    }else if(type == 4){
      app.TestBuriedPoint('yqlw_list_history','yqlw_list_pv')
      // app.TestBuriedPoint('yqlw_list_pv')
    }
    wx.navigateTo({
      url: '/pages/myactivities/myactivities?type=' + type
    });
    }
  },

  //to活动详情
  todetailsoftheevent:function(option){
    if (!this.data.island) {
      this.landbtn()
    } else {
    var activityId  = option.currentTarget.dataset.title
    var actType = option.currentTarget.dataset.acttype
    var type = option.currentTarget.dataset.type
    if (type==1 && actType == 12) {
      wx.navigateTo({
        url: '/pages/partySettingMemo/partySettingMemo?id=' + activityId
      });
    } else if (type == 1){
      wx.navigateTo({
        url: '/pages/register/register?id=' + activityId
      });
    } else if (type == 2 && actType !=1){
      wx.navigateToMiniProgram({
        appId: app.globalData.blessingAppId,
        envVersion: app.globalData.activityMiniEnvVersion,
        path: 'pages/hundredDetailed/hundredDetailed?id=' + activityId + '&type=' + actType,
        success(res) {
          console.log(res);
        }
      })
    } else if (type == 2 && actType == 1){
      wx.navigateToMiniProgram({
        appId: app.globalData.blessingAppId,
        envVersion: app.globalData.activityMiniEnvVersion,
        path: 'pages/ordinaryDetails/ordinaryDetails?id=' + activityId,
        success(res) {
          console.log(res);
        }
      })
    }
    
    console.log('活动ID', activityId, option)
    }
  },


  birthdayAllTap:function (e) {

  },

  birthdayevent: function (option) {
    var activityId = option.currentTarget.dataset.title
    wx.navigateTo({
      url: '/pages/partySettingMemo/partySettingMemo?id=' + activityId
    });
  },

//老用户
  //三条消息
  getThreeMessage: function(){
    var that = this
    app.req({
      url: "wechat/sysMessage/getUnreadMessage",
      method: "get",
      data: {},
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            ThreeMessage: res.data
          });
          // console.log("活动群通知",that.data.ThreeMessage)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  localtion: function(){
    app.TestBuriedPoint('yqlw_home_Location')
    wx.navigateTo({
      url: '/pages/areachoose/areachoose'
    });
  },
  messageIconTo:function(){
    app.TestBuriedPoint('yqlw_home_notice')
    if (!this.data.island) {
      this.landbtn()
    } else {
    wx.navigateTo({
      url: '/pages/mymessage/mymessage'
    });
    }
  },
  getRedPointStatus: function(){
    var that = this
    app.req({
      url: "wechat/sysMessage/getMessageType",
      method: "post",
      data: {},
      success: function (res) {
        if (200 == res.code) {
          if (res.data.allMessage == 0){
            that.setData({
              isRedPoint: false
            });
          }else{
            that.setData({
              isRedPoint: true
            });
          }          
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  getBannerList:function(){
    var that = this
    var data = {
      "type": 1 
    }
    app.req({
      url: "wechat/banner/listBanner",
      method: "post",
      data: data,
      success: function (res) {
        if (200 == res.code) {
          that.setData({ bannerList:res.data})
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },

  // 登录
  landbtn() {
    this.toggle('loginShow', true)
    this.selectComponent('#login').showClose()
  },
  toggleToast(e) {
    console.log(e.detail)
    if (!e.detail.loginShow){
      this.toggle('loginShow', false)
    }
    this.onShow()
  },
})